<%@ taglib tagdir="/WEB-INF/tags" prefix="onadake" %>

<onadake:layout page="home" css="/bootstrap-3.0.0/examples/jumbotron/jumbotron.css" >
  <div class="container">
    <p></p>
    <div class="row">
      <div id="friends" class="col-lg-2">
        <div>&nbsp;</div>
        <div>&nbsp;</div>
      </div>
      <div id="chat" class="col-lg-10">
        <form id="postMessageForm" role="form" class="form-horizontal">
          <div class="form-group">
            <div class="col-lg-12">
              <textarea class="form-control" rows="3" name="messageText" id="messageText"></textarea>
            </div>
          </div>
          <div id="messageFileUpload" class="form-group">
            <div class="col-lg-12">
              <input type="file" name="messageFile" id="messageFile" />
              <p class="help-block">Attach file</p>
            </div>
          </div>
          <button id="postMessageSubmitButton" type="submit" class="btn btn-default">Send</button>
        </form>
        <p></p>
        <div class="row">
          <div id="chatMessages" class="col-lg-12">
          </div>
        </div>
        <div class="row">
          <div id="loadMore" class="col-lg-12">
            <button id="loadMoreMessagesButton" class="btn btn-primary">Load more</button>        
          </div>
        </div>
      </div>
    </div>

    <hr/>
     
    <footer>
      <p>&copy; Onadake 2013</p>
    </footer>
  </div>

  <script type="text/javascript">
  $(document).ready(function() {
	  var friendsErrorReporter = new ErrorReporter('#friends');
	  var chatMessagesErrorReporter = new ErrorReporter('#chatMessages');
	  var loadMoreErrorReporter = new ErrorReporter('#loadMore');
    var postMessageErrorReporter = new ErrorReporter('#postMessageForm');
    
    var isFriendActive = function(code) {
      return $('#friends button[data-code="' + code + '"]').hasClass('btn-success');
    };
    
    var createMessageHtml = function(record) {
      var res = '<div data-ownerCode="###ownerCode" data-utcInsertTimestamp="###utcInsertTimestamp" class="media well" ###hide>' +
          '<div class="media-body"><h4 class="media-heading">###nick - ###timestamp</h4>###text</div></div>';
      res = res.replace(/###ownerCode/, record.ownerCode).
          replace(/###nick/, $('#friends button[data-code="' + record.ownerCode + '"]').html()).
          replace(/###hide/, isFriendActive(record.ownerCode) ? '' : 'style="display: none;"').
          replace(/###utcInsertTimestamp/, record.utcInsertTimestamp).
          replace(/###timestamp/, record.utcInsertTimestamp).
          replace(/###text/, record.text);
      return res;
    };
    
    var appendMessages = function(records) {
      for (var i = 0; i < records.records.length; ++i) {
        var html = createMessageHtml(records.records[i]);
        $('#chatMessages').append(html);
      };
    };

    var prependMessages = function(records) {
      for (var i = 0; i < records.records.length; ++i) {
        var html = createMessageHtml(records.records[i]);
        $('#chatMessages').prepend(html);
      };
    };

    // pulling live messages
    var pullLiveMessages = null;
    pullLiveMessages = function() {
    	  var ts = $('#chatMessages div:first').attr('data-utcInsertTimestamp');
        if (ts === undefined) {
          ts = '';
        }
        var reqData = {
          latestUtcInsertTimestamp : ts
        };
        chatMessagesErrorReporter.postJSON('${pageContext.request.contextPath}/user/selectLiveMessages', reqData, prependMessages)
          .complete(pullLiveMessages);
    };
    
	  // load friends
    $('#loadMoreMessagesButton').busy('');
    $.dataLoader({
      url              : '${pageContext.request.contextPath}/user/selectFriends',
      requestData      : {},
      from             : 0,
      limit            : null,
      requestLimit     : 999999999,
      errorReporter    : friendsErrorReporter,
      onLoadingStarted : function() {
        $('#friends').busy();
      },
      onLoadingDone    : function(data) {
        var html = '';
        for (var i = 0; i < data.numRecords; ++i) {
          var rec = data.records[i];
          html = html + '<div><button data-code="' + rec.code +'" type="button" class="btn btn-success btn-lg">' + rec.nick + '</button></div>';
        }
        $('#friends').html(html);
        $('#friends button').click(function(event) {
          event.preventDefault();
          $(this).toggleClass('btn-success');
          $(this).toggleClass('btn-danger');
          var code = $(this).attr('data-code');
          if (isFriendActive(code)) {
        	  $('#chatMessages > div[data-ownerCode="' + code + '"]').show();
          }
          else {
        	  $('#chatMessages > div[data-ownerCode="' + code + '"]').hide();
          }
        });

        // initial load of messages
        var reqData = {
          from : 0,
          limit : 100
        };
        var initialChatMessagesLoadingDone = function(data) {
          appendMessages(data);
          pullLiveMessages();
        };
        loadMoreErrorReporter.postJSON('${pageContext.request.contextPath}/user/selectMessages', reqData, initialChatMessagesLoadingDone)
          .complete(function () { $('#loadMoreMessagesButton').busy('hide'); } );
      },
      onLoadingComplete : function() { $('#friends').busy('hide'); }
    });

    // load more messages
    $('#loadMoreMessagesButton').click(function(event) {
    	$('#loadMoreMessagesButton').busy();
      var reqData = {
        from : 0,
        limit : 100,
        firstUtcInsertTimestamp : $('#chatMessages div:last').attr('data-utcInsertTimestamp')
      };
      loadMoreErrorReporter.clearErrors();
      loadMoreErrorReporter.postJSON('${pageContext.request.contextPath}/user/selectMessages', reqData, appendMessages)
        .complete(function () { $('#loadMoreMessagesButton').busy('hide'); } );
    });
    
    // post message
    var html5UploadSupported = !!(window.FileReader && window.FormData);
    if (!html5UploadSupported) {
    	$('#messageFileUpload').remove();
    }

    var getActiveFriendCodes = function() {
      var $buttons = $('#friends button.btn-success');
      var res = '';
      for (var i = 0; i < $buttons.length; ++i) {
        res = res + ',' + $buttons[i].getAttribute('data-code');
      }
      res = res.substring(1, res.length);
      return res;
    };
    
    $('#postMessageForm').submit(function (event) {
      event.preventDefault();
      $('#postMessageSubmitButton').busy();
      var targets = getActiveFriendCodes();
      var reqData = null;
      if (html5UploadSupported) {
    	  var files = ($('#messageFile')[0]).files;
        reqData = new FormData();
        reqData.append('targets', targets);
        reqData.append('text', $('#messageText').val());
        if (files[0] !== undefined && files[0] !== null) {
          reqData.append('file', files[0]);
        }
      }
      else {
        reqData = {
          targets : targets,
          text : $('#messageText').val()
        };
      }

      var postMessageSuccess = function() {
    	  $('#messageText').val('');
    	  $('#messageFile').val('');
      };
      postMessageErrorReporter.clearErrors();
      postMessageErrorReporter.postJSON('${pageContext.request.contextPath}/user/postMessage', reqData, postMessageSuccess)
          .complete(function() { $('#postMessageSubmitButton').busy('hide'); });
    });
    
  });
  </script>
  
  
</onadake:layout>